package com.heima.search.service.impl;

import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.dtos.HistorySearchDto;
import com.heima.search.pojos.ApUserSearch;
import com.heima.search.service.ApUserSearchService;
import com.heima.search.thread.AppThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class ApUserSearchServiceImpl  implements ApUserSearchService {

    @Autowired
    private MongoTemplate mongoTemplate;
    @Override
    public void insert(String keyword, Integer userId) {

        Query query = new Query();
        query.addCriteria(Criteria.where("keyword").is(keyword).and("userId").is(userId));
        ApUserSearch apUserSearch = mongoTemplate.findOne(query, ApUserSearch.class);
        if (apUserSearch == null) {
            ApUserSearch search = new ApUserSearch();
            search.setCreatedTime(new Date());
            search.setKeyword(keyword);
            search.setUserId(userId);
            mongoTemplate.save(search);
        } else {
            apUserSearch.setCreatedTime(new Date());
            mongoTemplate.save(apUserSearch);
        }
    }

    @Override
    public ResponseResult findAll() {
        Integer id = AppThreadLocalUtil.getUser().getId();

        Query query=new Query();
        query.addCriteria(Criteria.where("UserId").is(id));
        query.with(Sort.by("publishTime").descending());
        query.limit(10);
        List<ApUserSearch> apUserSearches = mongoTemplate.find(query, ApUserSearch.class);
        return ResponseResult.okResult(apUserSearches);
    }

    @Override
    public ResponseResult deleted(HistorySearchDto dto) {
        String id = dto.getId();
        Query query=new Query();
        query.addCriteria(Criteria.where("Id").is(id));
        ApUserSearch apUserSearch = mongoTemplate.findOne(query, ApUserSearch.class);
        mongoTemplate.remove(apUserSearch);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
